# Alexander F. Gazmararian
# afg2@princeton.edu

# Load packages
library(tidyverse)
library(modelsummary)
library(lmtest)
library(sandwich)
library(kableExtra)
library(margins)

# Load functions
source("code/fun/book_theme.r")
source("code/fun/savefig.r")
source("code/fun/fix_txt.r")
source("code/fun/coefnames4tables.r")

# Load CivicPulse data
cp <- readRDS("data/CivicPulse_Public.rds")

# Specify models

## NOTE: the following variables are only in the restricted access data (see README.txt): biden2020 + Census_area_college + log(Census_area_population) + Census_area_urban

f.base <- y ~ Age_cat + Woman + College + Minority_bin + PartySummary + Gov_type + biden2020 + Sample + Census_area_college + log(Census_area_population) + Census_area_urban
f.base.slim <- y ~ Age_cat + Woman + College + Minority_bin  + Gov_type +  Sample

# Check median answer
median(cp$Transparency, na.rm = TRUE)

# Create Figure 8.4
n_transp <- nrow(subset(cp, !is.na(Transparency_med)))
jobsplot <-
  cp %>%
  filter(!is.na(Transparency_med)) %>%
  mutate(transptreat = ifelse(transptreat == 1, "Transparency", "No Transparency")) %>%
  group_by(transptreat) %>%
  summarise(ate = mean(Transparency_med),
            se = sd(Transparency_med) / sqrt(n_transp),
            lb = ate + se * qnorm(.025),
            ub = ate + se * qnorm(0.975),
            lb90 = ate + se * qnorm(0.05),
            ub90 = ate + se * qnorm(.95)) %>%
  ggplot() +
  geom_errorbar(aes(x=transptreat, y=ate, ymin=lb, ymax=ub), width = 0) +
  geom_errorbar(aes(x=transptreat, y=ate, ymin=lb90, ymax=ub90), width = 0, size = 1.5) +
  geom_point(aes(x=transptreat,y=ate), size = 4) +
  coord_flip() +
  scale_y_continuous(labels = scales::percent) +
  labs(x = "", y = "Above median local jobs created") +
  book_theme
jobsplot
savefig(jobsplot, "8.4_figure_civicpulsetransp", height = 1.2, filepath = "figures/")

# Estimate regression models for online appendix
m <- list()

m[[1]] <- lm(Transparency_med ~ transptreat + Sample, cp)
m[[2]] <- lm(update(f.base.slim, Transparency_med ~ transptreat + .), cp)
#m[[3]] <- lm(update(f.base, Transparency_med ~ transptreat + .), cp)

m[[3]] <- lm(Transparency ~ transptreat + Sample, cp)
m[[4]] <- lm(update(f.base.slim, Transparency ~ transptreat + .), cp)
#m[[6]] <- lm(update(f.base, Transparency ~ transptreat + .), cp)

file <- "tables/ch8/ols_transparency_civicpulse.txt"
modelsummary(
  m,
  vcov = "HC2",
  stars = c("$^{\\dagger}$"=.2,"$^{+}$"=.1,"*"=0.02), # change symbols to make one-sided hypothesis tests clear
  gof_map = c("nobs", "adj.r.squared"),
  coef_map = coefnames,
  output = "latex",
  escape = FALSE
) %>%
  #add_header_above(c(" " = 1, "Above Median (=1)" = 3, "% Going to Locals" = 3)) %>%
  cat(., file = file)
fix_txt(file)
